import { createContext, useContext, useEffect, useState, type ReactNode } from "react"
import * as SQLite from 'expo-sqlite';
import { drizzle, ExpoSQLiteDatabase } from 'drizzle-orm/expo-sqlite';
import { copyDatabaseFromAssets } from "./init";



interface BookContextType {
    db: ExpoSQLiteDatabase<Record<string, never>> & {
        $client: SQLite.SQLiteDatabase;
    }
}

const BookContext = createContext<BookContextType | undefined>(undefined)

export const useBooks = () => {
    const context = useContext(BookContext)
    if (context === undefined) {
        throw new Error("useBook must be used within a BookProvider")
    }
    return context.db
}

export const BookProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
    let [db, setDb]: any = useState();
    useEffect(() => {
        let init = async () => {
            await copyDatabaseFromAssets()
            const expo = SQLite.openDatabaseSync('books.db');
            const db = drizzle(expo);
            setDb(db);
        }
        init()
    }, [])

    return db && <BookContext.Provider value={{ db }}>{children}</BookContext.Provider>
}